﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Quartz;
using MySql.Data.MySqlClient;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization;
using DevDefined.OAuth.Consumer;
using DevDefined.OAuth.Framework;
using DevDefined.OAuth.Tests;
using System.Web.Configuration;
using System.Configuration;
using System.Xml;
using C5;
using Common.Logging;
using System.IO;
using Quartz.Collection;
using Quartz.Impl;
using Quartz.Impl.Calendar;
using Quartz.Impl.Matchers;
using Quartz.Impl.Triggers;
using Quartz.Listener;
using Quartz.Simpl;
using Quartz.Spi;
using Quartz.Util;
using Quartz.Job;
using System.Net;
using System.Xml.Linq;


namespace Events
{
    public partial class Global : System.Web.HttpApplication
    {
        public static IScheduler _scheduler;

        INonceGenerator _nonceGenerator = new GuidNonceGenerator();

        public class GuidNonceGenerator : INonceGenerator
        {
            protected Random random = new Random();

            public string GenerateNonce(IOAuthConsumerContext context)
            {
                return Guid.NewGuid().ToString();
            }
        }


        public INonceGenerator NonceGenerator
        {
            get { return _nonceGenerator; }
            set { _nonceGenerator = value; }
        }


        public interface INonceGenerator
        {
            string GenerateNonce(IOAuthConsumerContext context);
        }

        //IOAuthSession CreateMeshPlaceContext()
        //{
        //    var consumerContext = new OAuthConsumerContext
        //    {
        //        ConsumerKey = "RUpS6PU9Ei8sgA8wZaziIg",
        //        SignatureMethod = SignatureMethod.HmacSha1,
        //        ConsumerSecret = "RBy_yuomJpdX32f1TG3TjNMaq08",
        //        Token = "k6GQelVpDeKEgFCUPcLbDFbYGtV6Vev-",
        //        TokenSecret = "7gF4Uoidu95J0HBbekbNYQ5AebE"


        //    };

        //    consumerContext.Nonce = NonceGenerator.GenerateNonce(consumerContext);
        //    //consumerContext.NonceGenerator=

        //    return new OAuthSession(consumerContext)
        //                  .RequiresCallbackConfirmation();
        //}



        protected void Application_Start(object sender, EventArgs e)
        {



           
           

            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
            _scheduler = schedulerFactory.GetScheduler();
            _scheduler.Start();
            AddJob();

        }

        public static void RequestPosts()
        {

            try
            {

                

                if (ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString() != "")
                {

                    MySqlConnection testCon = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
                    MySqlConnection testConTwo = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

                    testCon.Open();
                    testConTwo.Open();

                    //Random random = new Random();
                    //int num = random.Next(1000);

                    string cmdTextZip = "SELECT * FROM Mesh_Zip";
                    MySqlCommand cmdZipCodes = new MySqlCommand(cmdTextZip, testCon);
                    MySqlDataReader theReader;
                    MySqlDataReader theReaderDataInZip;

                    theReader = cmdZipCodes.ExecuteReader();

                    List<string> theZipCodesList = new List<string>();

                    while (theReader.Read())
                    {

                        theZipCodesList.Add(theReader[0].ToString());


                    }



                    string prevNewValue;

                    long j = 0;
                    string whatZipNext;

                    while (j < theZipCodesList.Count)

                                         
                    {

                       
                        j++;

                        try
                        {


                            XmlDocument xmlDoc = new XmlDocument();
                            xmlDoc.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"SettingsEvents.xml"));
                            //xmlDoc.Load("SettingsEvents.xml");
                            
                            XmlNodeList WhatZipCurrently;
                            XmlNodeList whatSearchTerm;
                            XmlNodeList whatZipCount;
                                                                                  
                            WhatZipCurrently = xmlDoc.GetElementsByTagName("theZipCodeRow");
                            whatSearchTerm = xmlDoc.GetElementsByTagName("Category");
                            whatZipCount = xmlDoc.GetElementsByTagName("ZipCodeCount");


                            string url = "http://api.eventful.com/rest/events/search?app_key=txV32NNGstV63pkS&keywords="+ whatSearchTerm.Item(0).InnerText + "&location=" + WhatZipCurrently.Item(0).InnerText + "&date=Future";

                            WebRequest req = HttpWebRequest.Create(url);
                            WebResponse res = req.GetResponse();
                            StreamReader sr = new StreamReader(res.GetResponseStream());

                            prevNewValue = whatZipCount.Item(0).InnerText;
                            

                            try
                            {

                                string newSt;
                                newSt = sr.ReadToEnd();

                                XmlDocument XmlNewdoc = new XmlDocument();
                                XmlNewdoc.LoadXml(newSt);

                                XmlNewdoc.PreserveWhitespace = false;

                                XmlNodeList xnList = XmlNewdoc.SelectNodes("/search/events/event");
                                //XmlNodeList xnListImage = XmlNewdoc.SelectNodes("/search/events/image");
                                string theTitle = "";
                                string theUrl = "";
                                string postImageUrl = "";
                                string theDesc = "";

                                DateTime todaysDate = DateTime.Now;
                                string jTheDate = todaysDate.ToString("yyyy/MM/dd");
                               

                                    if (xnList.Count == 0)
                                    {

                                        int theNewValueFirst = Convert.ToInt32(prevNewValue) + 1;

                                        XmlDocument xmlDocTwoFirst = new XmlDocument();
                                        xmlDocTwoFirst.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SettingsEvents.xml"));
                                        //xmlDocTwo.Load("SettingsEvents.xml");
                                        //XmlNodeList WhatZipCurrently;
                                        //XmlNodeList whatSearchTerm;

                                        string newValueFirst = Convert.ToString(theNewValueFirst);

                                        XmlNodeList nodeFirst;
                                        XmlNodeList node2First;

                                        nodeFirst = xmlDocTwoFirst.GetElementsByTagName("ZipCodeCount");

                                        //XmlNode node = xmlDoc.SelectSingleNode("Root/Configuration/ZipCodeCount");
                                        nodeFirst.Item(0).InnerText = newValueFirst;

                                        int thisValueFirst = Convert.ToInt32(newValueFirst);

                                        node2First = xmlDocTwoFirst.GetElementsByTagName("theZipCodeRow");
                                        node2First.Item(0).InnerText = theZipCodesList[thisValueFirst].ToString();

                                        xmlDocTwoFirst.Save(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SettingsEvents.xml"));


                                    }
                                
                               

                                foreach (XmlNode xn in xnList)
                                {
                                    try
                                    {
                                        theTitle = xn["title"].InnerText.Replace("'", "''");
                                    }
                                    catch (Exception theExce)
                                    {
                                        theTitle = "";
                                    }

                                    try
                                    {
                                        theUrl = xn["url"].InnerText;
                                    }
                                    catch (Exception theExce)
                                    {
                                        theUrl = "";
                                    }

                                    try
                                    {
                                        postImageUrl = xn["image"].InnerText;
                                        //var parts  = postImageUrl.Split('4848');
                                        int index = postImageUrl.IndexOf("4848");
                                        if (index > 0)
                                            postImageUrl = postImageUrl.Substring(0, index); 
                                                                                

                                        //postImageUrl = postImageUrl.Remove(postImageUrl.('4848'));
                                        
                                    }
                                    catch (Exception theExce)
                                    {
                                        postImageUrl = "";
                                    }

                                    try
                                    {
                                        theDesc = xn["description"].InnerText.Replace("'", "''");
                                    }
                                    catch (Exception theExce)
                                    {
                                        theDesc = "";
                                    }
                                    try
                                    {
                                        string cmdText = "INSERT INTO Mesh_Post (Post_Title ,Post_Date,Post_Link,Post_ImgURL,Post_Description,Post_Zip_Locale,UserNo,CategoryTitle) Values ('" + theTitle + "','" + jTheDate.ToString() + "','" + theUrl + "','" + postImageUrl + "','" + theDesc + "','" + WhatZipCurrently.Item(0).InnerText + "',320,'Events')";
                                        MySqlCommand cmd = new MySqlCommand(cmdText, testConTwo);

                                        cmd.ExecuteNonQuery();
                                    }
                                    catch (Exception newExce)
                                    {
                                        Console.WriteLine(newExce.Message.ToString());
                                    }
                                }


                                int theNewValue = Convert.ToInt32(prevNewValue) + 1;

                                XmlDocument xmlDocTwo = new XmlDocument();
                                xmlDocTwo.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SettingsEvents.xml"));
                                //xmlDocTwo.Load("SettingsEvents.xml");
                                //XmlNodeList WhatZipCurrently;
                                //XmlNodeList whatSearchTerm;

                                string newValue = Convert.ToString(theNewValue);



                                XmlNodeList node;
                                XmlNodeList node2;

                                node = xmlDocTwo.GetElementsByTagName("ZipCodeCount");

                                //XmlNode node = xmlDoc.SelectSingleNode("Root/Configuration/ZipCodeCount");
                                node.Item(0).InnerText = newValue;

                                int thisValue = Convert.ToInt32(newValue);

                                node2 = xmlDocTwo.GetElementsByTagName("theZipCodeRow");
                                node2.Item(0).InnerText = theZipCodesList[thisValue].ToString();

                                xmlDocTwo.Save(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SettingsEvents.xml"));



                             
                            }
                            finally
                            {
                                sr.Close();
                            }

                                                         

                            }

                        
                        catch (Exception theE)
                        {
                            if (theE.Message == "The remote server returned an error: (403) Forbidden.")
                            {

                            }
                            else
                            {

                                   
                                                                                                
                            }
                        }

                        
                    }
                    testCon.Close();
                    testConTwo.Close();
                    
                }


            }
            catch (Exception newExcept)
            {
               // throw newExcept.InnerException;



            }

        }


        internal class MyJob : IJob
        {
            public void Execute(IJobExecutionContext context)
            {

                //MySqlConnection testNP = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

                //testNP.Open();

                //string InserNEwCM = "INSERT INTO Mesh_Post (Post_Title ,Post_Date,Post_Link,Post_ImgURL,Post_Description,Post_Zip_Locale,UserNo,CategoryTitle) Values ('5','date','url','imageurl','thenisp','78045',320,'Restaurants')";
                //MySqlCommand cmdFinal = new MySqlCommand(InserNEwCM, testNP);

                //cmdFinal.ExecuteNonQuery();
                //testNP.Close();

                RequestPosts();

                // RequestPosts(); 
                //RequestPosts();

                // //const string zwsid = "X1-ZWz1dfzozk5amj_6jziz";
                //String url = "http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=X1-ZWz1dfzozk5amj_6jziz&citystatezip=78041";
                //HttpWebRequest Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(url);

                //string conString = "";

                //if (ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString() != "")
                //{

                //    MySqlConnection testCon = new MySqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

                //    testCon.Open();

                //    Random random = new Random();
                //    int num = random.Next(1000);

                //    string cmdText = "INSERT INTO Mesh_Category (CategoryTitle ,CategoryDescription) Values ('" + num + "','CatDesc')";
                //    MySqlCommand cmd = new MySqlCommand(cmdText, testCon);
                //    cmd.ExecuteNonQuery();

                //    testCon.Close();

                //}

            }
        }

        public static void AddJob()
        {

            IJob myJob = new MyJob();
            JobDetailImpl jobDetail = new JobDetailImpl("Events", "GroupNew", myJob.GetType());

            //  CronTriggerImpl trigger = new CronTriggerImpl("Trigger1", "Group1", "When to run it goes here");
            SimpleTriggerImpl trigger1 = new SimpleTriggerImpl("TriggerEvents", 950, TimeSpan.FromDays(1.00));
            //trigger1.SetNextFireTimeUtc(SystemTime.UtcNow());
            _scheduler.ScheduleJob(jobDetail, trigger1);

              // create job
         
  
            //    DateTimeOffset? nextFireTime = trigger.GetNextFireTimeUtc();
            //  Console.WriteLine("Next Fire Time:" + nextFireTime.Value);
        }


        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}